import store from '@/store'
import IM from '@/im'
import { mapGetters } from 'vuex'

const { IMEventType } = IM

const IM_Minxin = {
  mounted() {
    this.$im.on(this.IMListener)
  },
  beforeDestroy() {
    this.$im.off(this.IMListener)
  },
  computed: {
    ...mapGetters(['contacts']),
    ...mapGetters(['token'])
  },
  watch: {
    token: {
      handler(newVal) {
        if (!newVal) return

        this.$im.connect({
          force: true
        })
      },
      immediate: true
    }
  },
  methods: {
    IMListener(event) {
      const { type, data, msg } = event
      console.log('im', event)
      switch (type) {
        case IMEventType.CALL.onSession:
          const { targetId } = data

          const { userInfo } = this.contacts.find((c) => c.userId === targetId)

          this.$popup.show({
            type: 'calling',
            success: (popup) => {
              popup.setData({
                type: 'passive',
                data: userInfo
              })
            }
          })
          break
        case IMEventType.CALL.onSessionClose:
          this.$popup.hide('calling')
          break
        case IMEventType.SYSTEM.disconnected:
          this.$alert(msg, {
            confirmButtonText: '确定',
            callback: () => {}
          })
          break
        default:
          break
      }
    }
  }
}

export default IM_Minxin
